import json
import subprocess
import threading

from django.core import serializers
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt

from sjgapp import tool_sjg
from sjgapp.models import myansible, mylog


@csrf_exempt
def get_by_page(request):
    info = request.body
    info = json.loads(info)
    pagenow = int(info['pagenow'])
    pagesize = int(info['pagesize'])
    start = (pagenow-1)*pagesize
    end = (pagenow-1)*pagesize+pagesize
    search = info['search']
    myansibles = myansible.objects.filter(name__icontains=search)[start:end]
    myansibles = serializers.serialize('json', myansibles)

    counts = myansible.objects.filter(name__icontains=search).count()
    return HttpResponse(json.dumps( {"result": json.loads(myansibles), "allcount": counts} ) )

def ansible_run_local(command, pk):
    (status, output) = subprocess.getstatusoutput(command)
    mylogresult = mylog.objects.get(pk = pk)
    mylogresult.writeresult='done'
    mylogresult.save()
    return "true"

def ansible_run_remote(myparam):
    mylogresult = mylog.objects.get(pk=myparam['pk'])
    myinifile = '/tmp/ansible{0}.tmp'.format(mylogresult.pk)
    try:
        tool_sjg.ssh_copy_put(myparam['proxy'], myinifile, myinifile)
        tool_sjg.ssh_remote_command(myparam['proxy'], myparam['command'])
    except Exception as e:
        print(e)
        mylogresult.writeresult = 'done'
        mylogresult.save()
        return "fail"
    mylogresult.writeresult='done'
    mylogresult.save()
    return "Success"

def runit_by_id(request):
    id = request.GET.get('id')
    oneansible = myansible.objects.get(pk = id)
    mylogresult = mylog.objects.create(name=oneansible.name, proxy=oneansible.proxy)
    myinifile = '/tmp/ansible{0}.tmp'.format(mylogresult.pk)
    mylogfile = '/tmp/ansible{0}.log'.format(mylogresult.pk)
    mylogresult.logpath = mylogfile
    mylogresult.save()
    with open(myinifile, 'w') as f:
        f.write(oneansible.invent)
    command = """ ansible -i {0} {1} -m {2} -a '{3}' -f {4} &> {5} """.format(myinifile,
        oneansible.pattern,oneansible.module,oneansible.args.replace('\r',''),oneansible.forks, mylogfile)
    if oneansible.proxy != 'default':
        t1 = threading.Thread(target=ansible_run_remote, args=( {'proxy': oneansible.proxy, 'command': command, 'pk': mylogresult.pk}, ))
        t1.start()
        return HttpResponse(str(mylogresult.pk))
    else:
        t1 = threading.Thread(target=ansible_run_local, args=(command, mylogresult.pk))
        t1.start()
        return HttpResponse(str(mylogresult.pk))